<template>
  <div class="job-positions-container">
    <div class="header">
      <div class="left">
        <h2>岗位管理</h2>
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>添加岗位
        </el-button>
      </div>
      <div class="right">
        <el-input
          v-model="searchQuery"
          placeholder="搜索岗位标题"
          class="search-input"
          clearable
          @clear="handleSearch"
          @keyup.enter="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>
    </div>

    <el-card class="table-card">
      <el-table
        v-loading="loading"
        :data="positions"
        border
        stripe
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="title" label="岗位标题" min-width="150" />
        <el-table-column prop="category.name" label="岗位分类" width="120" />
        <el-table-column prop="teacher.name" label="发布教师" width="120" />
        <el-table-column prop="quota" label="招聘人数" width="100" />
        <el-table-column prop="salary" label="时薪" width="100">
          <template #default="{ row }">
            ¥{{ row.salary }}
          </template>
        </el-table-column>
        <el-table-column prop="workLocation" label="工作地点" width="150" />
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="审核状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="active" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getRecruitmentStatusType(row)">
              {{ getRecruitmentStatusText(row) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button-group>
              <el-button
                v-if="row.status === 'PENDING'"
                type="success"
                size="small"
                @click="handleReview(row)"
              >
                审核
              </el-button>
              <el-button
                type="primary"
                size="small"
                @click="handleEdit(row)"
              >
                编辑
              </el-button>
              <el-button
                type="danger"
                size="small"
                @click="handleDelete(row)"
              >
                {{ row.active ? '结束' : '删除' }}
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 岗位表单对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="650px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="岗位标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入岗位标题" />
        </el-form-item>
        <el-form-item label="岗位分类" prop="categoryId">
          <el-select 
            v-model="form.categoryId" 
            placeholder="请选择岗位分类"
            :loading="categoriesLoading"
          >
            <el-option
              v-for="item in categories"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="招聘人数" prop="quota">
          <el-input-number v-model="form.quota" :min="1" />
        </el-form-item>
        <el-form-item label="时薪" prop="salary">
          <el-input-number v-model="form.salary" :min="0" :precision="2" :step="0.5" />
        </el-form-item>
        <el-form-item label="工作时间" prop="workingHours">
          <el-input v-model="form.workingHours" placeholder="请输入工作时间" />
        </el-form-item>
        <el-form-item label="工作地点" prop="workLocation">
          <el-input v-model="form.workLocation" placeholder="请输入工作地点" />
        </el-form-item>
        <el-form-item label="开始日期" prop="startDate">
          <el-date-picker
            v-model="form.startDate"
            type="datetime"
            placeholder="请选择开始日期"
          />
        </el-form-item>
        <el-form-item label="结束日期" prop="endDate">
          <el-date-picker
            v-model="form.endDate"
            type="datetime"
            placeholder="请选择结束日期"
          />
        </el-form-item>
        <el-form-item label="岗位要求" prop="requirements">
          <el-input
            v-model="form.requirements"
            type="textarea"
            :rows="3"
            placeholder="请输入岗位要求"
          />
        </el-form-item>
        <el-form-item label="福利待遇" prop="benefits">
          <el-input
            v-model="form.benefits"
            type="textarea"
            :rows="3"
            placeholder="请输入福利待遇"
          />
        </el-form-item>
        <el-form-item label="岗位描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="4"
            placeholder="请输入岗位描述"
          />
        </el-form-item>
        <el-form-item label="发布教师" v-if="form.teacher">
          <el-input v-model="form.teacher.name" disabled />
        </el-form-item>
        <el-form-item label="审核状态" v-if="form.status">
          <el-tag :type="getStatusType(form.status)">
            {{ getStatusText(form.status) }}
          </el-tag>
        </el-form-item>
        <el-form-item label="审核意见" v-if="form.reviewComments">
          <el-input
            v-model="form.reviewComments"
            type="textarea"
            :rows="3"
            disabled
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button
          type="primary"
          :loading="submitting"
          @click="handleSubmit"
        >
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 审核对话框 -->
    <el-dialog
      title="岗位审核"
      v-model="reviewDialogVisible"
      width="500px"
    >
      <el-form
        ref="reviewFormRef"
        :model="reviewForm"
        :rules="reviewRules"
        label-width="100px"
      >
        <el-form-item label="审核结果" prop="approved">
          <el-radio-group v-model="reviewForm.approved">
            <el-radio :label="true">通过</el-radio>
            <el-radio :label="false">拒绝</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审核意见" prop="reviewComments">
          <el-input
            v-model="reviewForm.reviewComments"
            type="textarea"
            :rows="4"
            placeholder="请输入审核意见"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="reviewDialogVisible = false">取消</el-button>
        <el-button
          type="primary"
          :loading="reviewing"
          @click="submitReview"
        >
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="JobPositionList">
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search } from '@element-plus/icons-vue'
import { 
  getPositions,
  createPosition,
  updatePosition,
  deletePosition,
  reviewPosition
} from '@/api/admin/jobPosition'
import {
  getCategories
} from '@/api/admin/jobCategory'
import { formatDate } from '@/utils/format'

// 表格数据
const loading = ref(false)
const positions = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const searchQuery = ref('')
const categories = ref([])
const categoriesLoading = ref(false)

// 表单数据
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formRef = ref(null)
const submitting = ref(false)
const form = ref({
  id: null,
  title: '',
  categoryId: null,
  description: '',
  quota: 1,
  salary: 0,
  workingHours: '',
  workLocation: '',
  requirements: '',
  benefits: '',
  startDate: null,
  endDate: null,
  teacher: null,
  status: 'PENDING',
  reviewComments: '',
  active: true
})

// 表单验证规则
const rules = {
  title: [
    { required: true, message: '请输入岗位标题', trigger: 'blur' },
    { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  categoryId: [
    { required: true, message: '请选择岗位分类', trigger: 'change' }
  ],
  quota: [
    { required: true, message: '请输入招聘人数', trigger: 'blur' }
  ],
  salary: [
    { required: true, message: '请输入时薪', trigger: 'blur' }
  ],
  workingHours: [
    { required: true, message: '请输入工作时间', trigger: 'blur' }
  ],
  workLocation: [
    { required: true, message: '请输入工作地点', trigger: 'blur' }
  ],
  requirements: [
    { required: true, message: '请输入岗位要求', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入岗位描述', trigger: 'blur' }
  ],
  startDate: [
    { required: true, message: '请选择开始日期', trigger: 'change' }
  ]
}

// 获取岗位列表
const fetchPositions = async () => {
  try {
    loading.value = true
    const response = await getPositions({
      page: currentPage.value - 1,
      size: pageSize.value,
      search: searchQuery.value
    })
    positions.value = response.content || []
    total.value = response.totalElements || 0
  } catch (error) {
    console.error('Failed to fetch positions:', error)
    ElMessage.error('获取岗位列表失败')
  } finally {
    loading.value = false
  }
}

// 获取分类列表
const fetchCategories = async () => {
  try {
    categoriesLoading.value = true
    const response = await getCategories({
      page: 0,
      size: 100,
      search: ''
    })
    console.log('Categories response:', response)
    if (response && response.content) {
      categories.value = response.content
    } else {
      console.error('Invalid categories response:', response)
      ElMessage.warning('获取分类列表数据格式异常')
    }
  } catch (error) {
    console.error('Failed to fetch categories:', error)
    ElMessage.error(error.response?.data?.message || '获取分类列表失败')
  } finally {
    categoriesLoading.value = false
  }
}

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
  fetchPositions()
}

// 添加岗位
const handleAdd = () => {
  dialogTitle.value = '添加岗位'
  form.value = {
    id: null,
    title: '',
    categoryId: null,
    description: '',
    quota: 1,
    salary: 0,
    workingHours: '',
    workLocation: '',
    requirements: '',
    benefits: '',
    startDate: null,
    endDate: null,
    teacher: null,
    status: 'PENDING',
    reviewComments: '',
    active: true
  }
  dialogVisible.value = true
}

// 编辑岗位
const handleEdit = (row) => {
  dialogTitle.value = '编辑岗位'
  form.value = {
    ...row,
    categoryId: row.category.id
  }
  dialogVisible.value = true
}

// 删除岗位
const handleDelete = async (row) => {
  const action = row.active ? '结束' : '删除'
  try {
    await ElMessageBox.confirm(`确定要${action}该岗位吗？`, '警告', {
      type: 'warning'
    })
    await deletePosition(row.id)
    ElMessage.success(`${action}成功`)
    fetchPositions()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('Failed to delete position:', error)
      ElMessage.error(`${action}失败`)
    }
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitting.value = true
    
    if (form.value.id) {
      await updatePosition(form.value.id, form.value)
      ElMessage.success('更新成功')
    } else {
      await createPosition(form.value)
      ElMessage.success('添加成功')
    }
    
    dialogVisible.value = false
    fetchPositions()
  } catch (error) {
    console.error('Form submission failed:', error)
    ElMessage.error('提交失败')
  } finally {
    submitting.value = false
  }
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchPositions()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchPositions()
}

// 在组件挂载时获取数据
onMounted(() => {
  fetchCategories()
  fetchPositions()
})

// 获取状态类型
const getStatusType = (status) => {
  switch (status) {
    case 'PENDING':
      return 'warning'
    case 'APPROVED':
      return 'success'
    case 'REJECTED':
      return 'danger'
    default:
      return 'info'
  }
}

// 获取状态文本
const getStatusText = (status) => {
  switch (status) {
    case 'PENDING':
      return '待审核'
    case 'APPROVED':
      return '已通过'
    case 'REJECTED':
      return '已拒绝'
    default:
      return '未知'
  }
}

// 获取招聘状态类型
const getRecruitmentStatusType = (row) => {
  if (row.status !== 'APPROVED') {
    return 'info'
  }
  return row.active ? 'success' : 'warning'
}

// 获取招聘状态文本
const getRecruitmentStatusText = (row) => {
  if (row.status !== 'APPROVED') {
    return '未开始'
  }
  return row.active ? '招聘中' : '已结束'
}

// 审核相关数据
const reviewDialogVisible = ref(false)
const reviewFormRef = ref(null)
const reviewing = ref(false)
const selectedPosition = ref(null)
const reviewForm = ref({
  approved: true,
  reviewComments: ''
})

// 审核表单验证规则
const reviewRules = {
  reviewComments: [
    { required: true, message: '请输入审核意见', trigger: 'blur' }
  ]
}

// 打开审核对话框
const handleReview = (row) => {
  selectedPosition.value = row
  reviewForm.value = {
    approved: true,
    reviewComments: ''
  }
  reviewDialogVisible.value = true
}

// 提交审核
const submitReview = async () => {
  if (!reviewFormRef.value) return
  
  try {
    await reviewFormRef.value.validate()
    reviewing.value = true
    
    await reviewPosition(selectedPosition.value.id, reviewForm.value)
    ElMessage.success('审核成功')
    reviewDialogVisible.value = false
    fetchPositions()
  } catch (error) {
    console.error('Review submission failed:', error)
    ElMessage.error('审核失败')
  } finally {
    reviewing.value = false
  }
}
</script>

<style scoped>
.job-positions-container {
  padding: 20px;
}

.header {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.search-input {
  width: 300px;
}

.table-card {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-button-group) {
  .el-button {
    padding: 5px 12px;
  }
}

:deep(.el-form-item) {
  margin-bottom: 20px;
}
</style> 